// pages/home/cart.js
const api = require("../../request/api")
const request = require("../../request/request")
const App = getApp();
const util = require("../../utils/util")
Page({

    /**
     * 页面的初始数据
     */
    data: {
        barHeight: App.globalData.paddingTop,

        page: 1,
        page_size: 15,
        selected_list: [],
        buying_number: 1,

        // 购物车信息
        cart_data: {},
        // 购物车商品列表
        cart_list: [],

        // 更多的推荐商品列表
        good_list: [],
        uid: '',
        total_price: 0,
        if_selected_all: false,
        number: 0,
        if_touching: false,
        styledata: {
            "bg_color": "white",
            "color": "#000",
            "name": "购物车"
        },

        vhNum: 10,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

        const that = this
        wx.getSystemInfo({
            success(res) {
                // console.log('购物车机型', res.safeArea.bottom);
                // 获取设备最底部，响应式设置购物车结算栏位置
                // 思路：定义固定定位，top:最底部、利用translateY上移 底部栏+结算栏的高度
                let screenBottom = res.safeArea.bottom

                that.setData({
                    screenBottom
                })
            }
        })

        this.init_data()
        this.get_cart_list()
        this.get_goods_list()
    },
    init_data() {
        this.setData({
            uid: App.globalData.uid || util.getAppValue('userInfo').uid,
            if_touching: false
        })
    },
    get_goods_list() {
        let params = {
            page: this.data.page,
            limit: this.data.page_size,
            type: 'default',
            // brand_id: 2
        }
        request.post(api.goods_more, params).then(res => {
            if (res.length == 0) {
                this.setData({
                    noMore: true
                })
                util.showToast('暂无更多相关商品')
                return
            }
            for (var i = 0; i < res.length; i++) {
                let mx = parseInt(Math.random() * 10) / 10
                let youhui = res[i].sell_price * (mx * 0.04 + 0.08)
                res[i].youhui = youhui.toFixed(2)
            }

            let list = this.data.good_list
            let new_list = list.concat(res)
            this.setData({
                good_list: new_list
            })
        })
    },
    go_home_button() {
        wx.switchTab({
            url: '/pages/home/classify',

        })
    },
    change_button_color() {
        this.setData({
            if_touching: true
        })
    },
    reset_button_color() {
        this.setData({
            if_touching: false
        })
    },

    handleChangeCart() {
        if (typeof this.getTabBar === 'function' &&
            this.getTabBar()) {
            this.getTabBar().setData({
                cartnum: App.globalData.cartnum,
                // selected: 0
            })
        }
    },

    // 商品列表组件点击加入购物车
    async cart_add(e) {
        if (!this.data.uid) {
            util.showToast('请登录后再添加购物车哦')
            return
        }
        let id = e.detail.currentTarget.dataset.id
        let goodDetail = await request.post(api.goods_details, { id })
        if (goodDetail.store_nums <= 0) {
            wx.showToast({
                title: '该商品暂无库存，请挑选别的心仪商品吧',
                icon: 'none',
                duration: 2000
            });
            return
        }

        // 筛选最低价格规格id，默认选最低规格
        let temArr = []
        goodDetail.products_array.forEach(item => {
            temArr.push(item.sell_price)
        });
        let lowestProPrice = Math.min(...temArr)
        let lowestIndex = temArr.indexOf(lowestProPrice)
        let skuid = goodDetail.products_array[lowestIndex].id
        // console.log('skuid', skuid);

        let params = {
            goods_id: id,
            uid: this.data.uid,
            goods_sku_id: skuid
        }
        let res = await request.post(api.cart_add, params)
        if (res) {
            let cartRes = await request.post(api.cart_list, { uid: this.data.uid })
            // console.log(cartRes);
            App.globalData.cartnum = cartRes.total_goods_nums

            this.handleChangeCart()
        }
        util.showToast("已加入购物车")
    },
    go_detail_from_component(e) {
        let id = e.detail.currentTarget.dataset.id
        wx.navigateTo({
            url: '/pages/good/detail?id=' + id,
        })
    },
    go_detail(e) {
        let id = e.currentTarget.dataset.id
        if (!id) {
            util.showToast('所选商品暂无记录')
            return
        }
        wx.navigateTo({
            url: '/pages/good/detail?id=' + id,
        })
    },


    async get_cart_list() {
        util.showLoading("正在加载")
        let params = {
            uid: this.data.uid
        }
        let res = await request.post(api.cart_list, params)
        let goods_list = res.goods_list
        // 循环中有异步操作，所以使用原生for循环
        // for (let i = 0; i < goods_list.length; i++) {
        //     goods_list[i].discountPrice = (goods_list[i].sell_price * this.data.discount).toFixed(2)
        //     let gooddetail = await request.post(api.goods_details, { id: goods_list[i].goods_id })
        //     let products = gooddetail.products_array
        //     products.forEach(pitem => {
        //         if (pitem.id == goods_list[i].product_id) {
        //             goods_list[i].pname = pitem.name
        //             return
        //         }
        //     });
        // }
        util.hideLoading()
        this.setData({
            cart_list: goods_list,
            cart_data: res
        })

        // 更新购物车商品数全局变量 
        App.globalData.cartnum = res.total_goods_nums


        // 保证变化购物车商品增减数量时不重置
        if (this.data.selected_list.length == 0) {
            let selected_list = []
            for (let item in this.data.cart_list) {
                selected_list.push(false)
            }
            this.setData({
                selected_list
            })
            // console.log('dfd', this.data.selected_list);
        }
        this.counting_price()
    },
    get_select_list() {

    },
    counting_price() {
        // console.log(this.data.cart_list)
        let selected_list_is_selected = this.data.selected_list
        let selected_list = this.data.cart_list
        let number = 0
        let total_price = 0
        for (let i in selected_list) {
            if (selected_list_is_selected[i]) {
                if (this.data.cart_list.length != 0) {
                    let single_price = this.data.cart_list[i].sell_price * this.data.cart_list[i].buy_num
                    total_price += single_price
                    number += this.data.cart_list[i].buy_num
                }
            }
        }
        total_price = parseFloat(total_price.toFixed(2))
        // console.log('ddddgfdgd', total_price);
        this.setData({
            total_price,
            number
        })
    },
    async minus(e) {
        let index = e.currentTarget.dataset.index
        let params = {
            uid: this.data.uid,
            goods_id: e.currentTarget.dataset.goods_id,
            goods_sku_id: this.data.cart_list[index]['product_id']
        }
        let res = await request.post(api.cart_minus, params)
        if (res) {
            let cartRes = await request.post(api.cart_list, { uid: this.data.uid })
            // console.log(cartRes);
            App.globalData.cartnum = cartRes.total_goods_nums
            this.handleChangeCart()
        }
        this.get_cart_list()
    },

    selecting(e) {
        let index = e.currentTarget.dataset.index
        let selected_list = this.data.selected_list
        selected_list[index] = !selected_list[index]
        this.setData({
            selected_list
        })
        this.counting_price()
        this.get_selected_all()
    },
    go_pay() {
        if (this.data.if_selected_all) {
            let url = '/pages/order/pay?type=' + '0'
            wx.navigateTo({
                url: url,
            })
        }
        // 多个商品订单
        else {
            let goodlist = this.data.cart_list
            let goodarr = []
            this.data.selected_list.forEach((item, index) => {
                if (item) {
                    goodarr.push({
                        id: goodlist[index].goods_id,
                        num: goodlist[index].buy_num,
                        product_id: goodlist[index].product_id
                    })
                }
            });
            let goodstr = JSON.stringify(goodarr)
            // console.log(goodstr);

            let url = `/pages/order/pay?type=2&goodstr=${goodstr}`
            wx.navigateTo({
                url: url,
            })
        }

    },

    all_picking() {
        this.setData({
            if_selected_all: !this.data.if_selected_all
        })
        let selected_list = []
        let if_selected = this.data.if_selected_all ? true : false
        for (let i in this.data.cart_list) {
            selected_list.push(if_selected)
        }
        this.setData({
            selected_list
        })
        this.counting_price()
    },

    // 直接输入商品数量
    async inputNum(e) {
        let value = e.detail.value
        let goodid = e.currentTarget.dataset.goods_id
        let originnum = e.currentTarget.dataset.originnum
        let index = e.currentTarget.dataset.index

        let sendPath = ''
        if (value - originnum > 0) {
            sendPath = api.cart_add
        } else if (value - originnum < 0) {
            sendPath = api.cart_minus
        } else {
            // 未改变购物数量，直接退出
            return
        }
        let num = Math.abs(value - originnum);
        let params = {
            uid: this.data.uid,
            goods_id: goodid,
            goods_num: num,
            goods_sku_id: this.data.cart_list[index]['product_id']
        }
        let res = await request.post(sendPath, params)
        if (res) {
            let cartRes = await request.post(api.cart_list, { uid: this.data.uid })
            // console.log(cartRes);
            App.globalData.cartnum = cartRes.total_goods_nums
            this.handleChangeCart()

        }
        this.get_cart_list()
    },

    async plus(e) {
        let index = e.currentTarget.dataset.index
        let params = {
            uid: this.data.uid,
            goods_id: e.currentTarget.dataset.goods_id,
            goods_sku_id: this.data.cart_list[index]['product_id']
        }
        let res = await request.post(api.cart_add, params)
        if (res) {
            let cartRes = await request.post(api.cart_list, { uid: this.data.uid })
            // console.log(cartRes);
            App.globalData.cartnum = cartRes.total_goods_nums
            this.handleChangeCart()

        }
        this.get_cart_list()
    },

    async cancel(e) {
        util.showLoading('正在删除')
        let selected_list = this.data.selected_list
        let id = e.currentTarget.dataset.goods_id
        let index = e.currentTarget.dataset.index
        let params = {
            uid: this.data.uid,
            //deleteGoods: [{goods_id: id}],
            goods_id: e.currentTarget.dataset.goods_id,
            // goods_sku_id: 0
        }
        let res = await request.post(api.cart_delete, params)
        selected_list.splice(index, 1)
        this.setData({
            selected_list
        })
        if (res) {
            let cartRes = await request.post(api.cart_list, { uid: this.data.uid })
            // console.log(cartRes);
            App.globalData.cartnum = cartRes.total_goods_nums
            this.handleChangeCart()

        }
        this.get_cart_list()
    },

    get_selected_all() {
        let selected_list = this.data.selected_list

        let flag = true
        for (let i of selected_list) {
            if (i == false) {
                flag = false
                break
            }
        }
        this.setData({
            if_selected_all: flag
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    all_cancel() {
        this.setData({
            if_selected_all: false
        })
        let selected_list = []
        let if_selected = this.data.if_selected_all ? true : false
        for (let i in this.data.cart_list) {
            selected_list.push(if_selected)
        }
        this.setData({
            selected_list
        })
        this.counting_price()
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: async function () {
        this.init_data()
        await this.get_cart_list()

        // 自定义底部栏保证选择无误的代码
        if (typeof this.getTabBar === 'function' &&
            this.getTabBar()) {
            this.getTabBar().setData({
                cartnum: App.globalData.cartnum,
                selected: 3
            })
        }

        // this.get_selected_all()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        // console.log('隐藏');
        this.all_cancel()
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        if (!this.data.noMore) {
            this.setData({
                page: ++this.data.page
            })
            this.get_goods_list();
        }
    },

    /**
     * 用户点击右上角分享
     */
    // onShareAppMessage: function () {

    // }
})